package com.hmall.gateway.filter;

import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
/*
使用过滤器验证是否携带token
 */
@Configuration
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求头
        ServerHttpRequest request = exchange.getRequest();
        //判断是否要放行
        if (isExclude(request.getPath().toString())) {
            //放行
                return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }

        Long userId=null;
        //解析并且校验token
        try {
             userId = jwtTool.parseToken(token);
            System.out.println(userId);
        } catch (Exception e) {
            //如果无效,出异常就拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //有效传递用户消息
        String userInfo = userId.toString();
        ServerWebExchange exchange1 = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        //放行
        return  chain.filter(exchange1);
    }
    //判断是否需要放行的路径
    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String pathPattern : excludePaths) {
            if (antPathMatcher.match(pathPattern,path)) {
                return true;
            }
        }
        return false;
    }
}
